<template>
  <div class="c-2dh22l">
    <NavBar :isShowLeft="false">
      <template slot="left">
        <van-icon name="arrow-left" @click="handleBack" />
      </template>
      <template slot="content">
        <div>{{ productInfo.productName }}</div>
      </template>
    </NavBar>
    <Loading :loading="loading">
      <div class="c-xt5xxy">
        <div
          class="
            c-xt5xxy-header
            flex-row flex-align-center flex-justify-between
          "
        >
          <div>{{ productInfo.productName }}</div>
        </div>
        <van-form ref="formInfo">
          <div>
            <div
              class="c-0i1rte-list"
              v-for="(item, index) in riskList"
              :key="index"
            >
              <div class="flex-row flex-align-center flex-justify-between">
                <div
                  class="c-0i1rte-list-header"
                  @click="item.isShow = !item.isShow"
                >
                  <van-icon
                    class="c-0i1rte-list-header-icon"
                    name="arrow"
                    v-show="item.isShow"
                  />
                  <van-icon
                    class="c-0i1rte-list-header-icon"
                    name="arrow-down"
                    v-show="!item.isShow"
                  />
                  <span
                    v-if="item.prFlag === 'M'"
                    class="c-0i1rte-list-header-title"
                  >
                    主险
                  </span>
                  <span v-else class="c-0i1rte-list-header-title">
                    附加险{{ index }}
                  </span>
                </div>

                <div
                  v-if="item.prFlag === 'R'"
                  @click="delRiskItem(index, item.riskId)"
                >
                  <div class="c-0i1rte-list-header-del">删除</div>
                </div>
              </div>
              <div v-show="!item.isShow">
                <van-cell
                  title="险种"
                  is-link
                  @click="handleVisible('riskType', index)"
                >
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    v-model="item.riskId"
                    :rules="formRules.noEmptyRules"
                  >
                    <template #input>
                      <PeoInsured
                        ref="riskType"
                        title="险种类型"
                        backType="obj"
                        @confirm="
                          value =>
                            handleSelect(value, 'riskId', riskList, index)
                        "
                        :defaultValue="item.riskId"
                        :columns="
                          item.prFlag === 'M'
                            ? mainRiskTypeList
                            : AdditionalRiskTypeList
                        "
                      />
                    </template>
                  </van-field>
                </van-cell>
                <van-cell
                  title="保险期间"
                  is-link
                  @click="
                    handleVisible('insurancePeriodType', index, item.riskId)
                  "
                >
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    v-model="item.insurancePeriodId"
                    :rules="formRules.noEmptyRules"
                  >
                    <template #input>
                      <PeoInsured
                        ref="insurancePeriodType"
                        title="保险期间类型"
                        @confirm="
                          value =>
                            handleConfirm(
                              value,
                              'insurancePeriodId',
                              riskList,
                              index
                            )
                        "
                        :defaultValue="item.insurancePeriodId"
                        :columns="
                          getDataList(item.riskId).insurancePeriodTypeList
                        "
                      />
                    </template>
                  </van-field>
                </van-cell>
                <van-cell
                  title="缴费方式"
                  is-link
                  @click="handleVisible('paymentWay', index, item.riskId)"
                >
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    v-model="item.paymentWay"
                    :rules="formRules.noEmptyRules"
                  >
                    <template #input>
                      <PeoInsured
                        ref="paymentWay"
                        title="缴费方式"
                        @confirm="
                          value =>
                            handleConfirm(value, 'paymentWay', riskList, index)
                        "
                        :defaultValue="item.paymentWay"
                        :columns="getDataList(item.riskId).paymentWayList"
                      />
                    </template>
                  </van-field>
                </van-cell>
                <van-cell
                  title="缴费年期"
                  is-link
                  @click="handleVisible('payPeriodId', index, item.riskId)"
                >
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    v-model="item.payPeriodId"
                    :rules="formRules.noEmptyRules"
                  >
                    <template #input>
                      <PeoInsured
                        ref="payPeriodId"
                        title="缴费年期"
                        @confirm="
                          value =>
                            handleConfirm(value, 'payPeriodId', riskList, index)
                        "
                        :defaultValue="item.payPeriodId"
                        :columns="getDataList(item.riskId).payPeriodTypeList"
                      />
                    </template>
                  </van-field>
                </van-cell>
                <van-cell title="保额">
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    type="number"
                    v-model="item.sumAssured"
                    :rules="formRules.noEmptyRules"
                  ></van-field>
                </van-cell>
                <van-cell title="保费">
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    type="number"
                    v-model="item.premium"
                    :rules="formRules.noEmptyRules"
                  ></van-field>
                </van-cell>
                <van-cell
                  title="被保人"
                  is-link
                  @click="handleVisible('partIds', index, item.riskId)"
                >
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    type="number"
                    :value="item.partId"
                    :rules="formRules.noEmptyRules"
                  >
                    <template #input>
                      <PeoInsured
                        ref="partIds"
                        title="被保人"
                        multi
                        @confirm="
                          value =>
                            handleConfirm(value, 'partIds', riskList, index)
                        "
                        :defaultValue="item.partIds"
                        :columns="getDataList(item.riskId).peopleList"
                      />
                    </template>
                  </van-field>
                </van-cell>
              </div>
            </div>
            <div class="c-0i1rte-list-header-add" @click="handleAdd">
              <van-icon class="c-0i1rte-list-header-icon" name="plus" />
              添加附加险
            </div>
          </div>
        </van-form>
      </div>
      <div class="c-0i1rte-bottom">
        <div class="flex-row flex-align-center flex-justify-between">
          <div class="c-0i1rte-bottom-content">
            累计保费:
            <span class="c-0i1rte-bottom-content-txt">{{ totalPrem }}元</span>
          </div>
          <div class="c-0i1rte-bottom-next" @click="handleMenu">下一步</div>
        </div>
      </div>
    </Loading>
  </div>
</template>
<script>
import NavBar from '@/components/h5header'
import PeoInsured from '@/components/peoInsured'
import { mapGetters, mapState, mapActions, mapMutations } from 'vuex'
import API from '@/services/h5/product'
import Loading from '@/components/data-loading'
export default {
  components: { NavBar, PeoInsured, Loading },
  data() {
    return {
      activeName: [],
      formRules: {
        noEmptyRules: [{ required: true, message: '不能为空' }]
      },
      riskTypeList: [],
      AdditionalRiskTypeList: [],
      mainRiskTypeList: []
    }
  },
  computed: {
    ...mapGetters('product', ['productInfo']),
    ...mapState('product', ['riskList']),
    ...mapState('loading', ['loading']),
    totalPrem() {
      const total = this.riskList.reduce((p, c) => {
        return Number(p) + Number(c.premium)
      }, 0)
      return total
    }
  },
  created() {
    this.init()
  },
  methods: {
    ...mapActions('product', ['getProductDetailInfo']),
    ...mapMutations('loading', ['setLoading']),
    async init() {
      this.setLoading(true)
      this.getProductDetailInfo({
        contractId: this.$route.query.contractId
      })
      let riskRes = await API.getRiskQuery({
        contractId: this.$route.query.contractId
      })
      if (riskRes.data.code === 1000) {
        let rule = {
          riskId: 'code',
          riskName: 'codeName'
        }
        this.riskTypeList = this.changeProp(rule, riskRes.data.data)
        // 主险
        this.mainRiskTypeList = this.riskTypeList.filter(item => {
          return item.prFlag === 'M'
        })
        // 附加险
        this.AdditionalRiskTypeList = this.riskTypeList.filter(item => {
          return item.prFlag === 'R'
        })
        // 必须添加的险种
        // const data = this.riskTypeList.filter(item => item.isMandatory == 'Y')
        // if (data && data.length !== 0) {
        //   data.map(item => {
        //     this.riskList.push({
        //       isShow: true,
        //       riskId: item.riskId,
        //       insurancePeriodId: '',
        //       payPeriodId: '',
        //       paymentWay: '',
        //       sumAssured: '',
        //       premium: '',
        //       partIds: [],
        //       prFlag: item.prFlag,
        //       partId: ''
        //     })
        //   })
        // }
      }
      this.setLoading(false)
    },
    handleBack() {
      this.$dialog
        .confirm({
          title: '此页面信息未保存，确认离开页面吗'
        })
        .then(() => {
          this.$router.go(-1)
          // this.$router.push(
          //   `/productOffline?contractId=${this.$route.query.contractId}`
          // )
        })
        .catch(() => {})
    },
    handleMenu() {
      this.$refs.formInfo
        .validate()
        .then(async () => {
          let params = {
            contractId: this.$route.query.contractId,
            risks: this.riskList.map(
              ({
                insurancePeriodId,
                partIds,
                payPeriodId,
                paymentWay,
                premium,
                riskId,
                sumAssured
              }) => {
                return {
                  insurancePeriodId,
                  partIds,
                  payPeriodId,
                  payWayId: paymentWay,
                  premium,
                  riskId,
                  sumAssured
                }
              }
            )
          }
          let res = await API.saveRiskInfo(params)
          this.setLoading(true)
          if (res.data && res.data.code === 1000) {
            this.setLoading(false)
            let path = `/productOffline/policyDistribution?contractId=${this.$route.query.contractId}`
            this.$router.push({
              path
            })
          }
        })
        .catch(() => {})
    },
    handleAdd() {
      if (this.AdditionalRiskTypeList.length === 0) {
        this.$dialog.alert({
          message: '该产品没有附加险',
          showCancelButton: false
        })
        return false
      }
      this.riskList.push({
        isShow: true,
        riskId: '',
        insurancePeriodId: '',
        payPeriodId: '',
        paymentWay: '',
        sumAssured: '',
        premium: '',
        partIds: [],
        prFlag: 'R',
        partId: ''
      })
    },
    delRiskItem(index, riskId) {
      const value = this.riskTypeList.find(item => item.riskId == riskId)
      if (value && value.isMandatory == 'Y') {
        this.$dialog
          .alert({
            message: '该险种不可删除',
            showCancelButton: false
          })
          .catch(() => {})
      } else {
        this.$dialog
          .alert({
            message: '是否确认删除该附加险?',
            showCancelButton: true
          })
          .then(() => {
            this.riskList.splice(index, 1)
          })
          .catch(() => {})
      }
    },
    handleVisible(type, index, riskId) {
      if (riskId || riskId === undefined) {
        this.$refs[type][index].visible = true
      } else {
        this.$dialog.alert({
          message: '请先选择险种',
          showCancelButton: false
        })
      }
    },
    handleSelect(value, prop, data, index) {
      data[index][prop] = value.code
    },
    handleConfirm(value, prop, data, index) {
      if (prop === 'partIds') {
        data[index]['partId'] = value.join(',')
      }
      data[index][prop] = value
    },

    changeProp(rule, data) {
      let result = []
      data.map(item => {
        let obj = {}
        for (let i in rule) {
          obj[rule[i]] = item[i]
        }
        result.push({
          ...obj,
          ...item
        })
      })
      return result
    },
    getDataList(riskId) {
      const value = this.riskTypeList.find(item => item.riskId == riskId)
      // 被保人
      let rule1 = {
        id: 'code',
        insurancePeriod: 'codeName'
      }
      let rule2 = {
        id: 'code',
        payWay: 'codeName'
      }
      let rule3 = {
        id: 'code',
        paymentPeriod: 'codeName'
      }
      let rule4 = {
        partId: 'code',
        name: 'codeName'
      }
      if (!value) {
        return {
          insurancePeriodTypeList: [],
          paymentWayList: [],
          payPeriodTypeList: [],
          peopleList: []
        }
      } else {
        return {
          insurancePeriodTypeList: this.changeProp(
            rule1,
            value.insurancePeriods
          ),
          paymentWayList: this.changeProp(rule2, value.payWays),
          payPeriodTypeList: this.changeProp(rule3, value.payPeriods),
          peopleList: this.changeProp(rule4, value.parts)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.c-2dh22l {
  background: #fafafa;
  box-sizing: border-box;
  height: 100%;
  position: relative;
  &-bottom {
    width: 345px;
    height: 50px;
    line-height: 50px;
    border-radius: 4.5px;
    background: @c-color-primary;
    color: #fff;
    font-size: 17px;
    font-weight: bold;
    text-align: center;
    margin-top: 15px;
  }
}
.c-xt5xxy {
  background: #fff;
  padding: 15px;
  box-shadow: rgba(0, 0, 0, 0.05) 0 1px 2px 0;
  height: calc(100vh - 80px - 38px);
  overflow-y: scroll;
  &-header {
    font-size: 19px;
    color: #000;
  }
}
.c-0i1rte {
  &-list {
    &-header {
      &-icon {
        font-size: 15px;
      }
      &-title {
        font-size: 16px;
        font-weight: bold;
      }
      &-add,
      &-del {
        background: @c-color-primary;
        padding: 2px 10px;
        color: #fff;
        font-size: 14px;
        border-radius: 10px;
      }
      &-add {
        margin-top: 15px;
        height: 40px;
        line-height: 40px;
      }
    }
    &-item {
      &-input {
        padding: 0;
      }
    }
  }
  &-bottom {
    position: fixed;
    bottom: 0;
    height: 50px;
    width: 375px;
    line-height: 50px;
    background: #fff;
    font-size: 15px;
    box-shadow: rgba(0, 0, 0, 0.07) 0 -1px 2px 0;
    &-content {
      padding-left: 15px;
      &-txt {
        color: @c-color-primary;
      }
    }
    &-next {
      width: 100px;
      text-align: center;
      background: @c-color-primary;
      color: #fff;
    }
  }
}
</style>
